/**
 * 
 */

package com.wutianyi.taskqueue.dao.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.wutianyi.taskqueue.constants.TaskStatus;
import com.wutianyi.taskqueue.dao.TaskDao;
import com.wutianyi.taskqueue.dao.TaskMapper;
import com.wutianyi.taskqueue.dataobject.TaskQueueDO;

/**
 * @author wutianyi
 * 
 */
public class TaskDaoImpl implements TaskDao<TaskQueueDO> {

	private TaskMapper	taskMapper;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.duowan.zone.taskqueue.dao.TaskDao#addTask(com.duowan.zone.rpc.task.TaskDefinition)
	 */
	public void addTask(TaskQueueDO task) {

		if(null == task) {
			return;
		}

		taskMapper.addTask(task);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.duowan.zone.taskqueue.dao.TaskDao#batchAddTasks(java.util.List)
	 */
	public void batchAddTasks(List<TaskQueueDO> tasks, int status) {

		if(null == tasks || 0 == tasks.size()) {
			return;
		}

		taskMapper.batchAddTasks(tasks, status);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.duowan.zone.taskqueue.dao.TaskDao#listTasks(int)
	 */
	public List<TaskQueueDO> listTasks(int size, int status) {

		if(0 == size) {
			return Collections.EMPTY_LIST;
		}
		return taskMapper.listTasks(size, status);
	}

	public void setTaskMapper(TaskMapper taskMapper) {

		this.taskMapper = taskMapper;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.duowan.zone.taskqueue.dao.TaskDao#updateTasksStatus(java.util.List, int)
	 */
	public void updateTasksStatus(List<String> taskIds, int newStatus) {

		if(null == taskIds || 0 == taskIds.size()) {
			return;
		}

		taskMapper.updateTasksStatus(taskIds, newStatus);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.duowan.zone.taskqueue.dao.TaskDao#removeTask(java.lang.String)
	 */
	public int removeTask(String taskId) {

		return taskMapper.removeTask(taskId);
	}

	/*
	 * (non-Javadoc)
	 * 增加事务控制
	 * 
	 * @see com.duowan.zone.taskqueue.dao.TaskDao#listTasksAndChangeStatus(int, int)
	 */
	public List<TaskQueueDO> listTasksAndChangeStatus(int size, int status, TaskStatus newStatus) {

		if(0 == size) {
			return Collections.EMPTY_LIST;
		}
		List<TaskQueueDO> tasks = taskMapper.listTasks(size, status);

		if(null == tasks || 0 == tasks.size()) {
			return Collections.EMPTY_LIST;
		}

		List<String> taskIds = new ArrayList<String>(tasks.size());

		for(TaskQueueDO task : tasks) {
			taskIds.add(task.getTaskId());
		}

		taskMapper.updateTasksStatus(taskIds, newStatus.getValue());
		return tasks;
	}

	public static void main(String[] args) {

	}

}
